import { ref, onMounted, onBeforeUnmount, onActivated, onDeactivated } from 'vue'
import { debounce } from '@/utils'

export default function useResize(chartRef) {
  const sidebarElm = ref(null)
  let resizeHandler = null

  // 调整图表大小
  const resize = () => {
    chartRef.value?.resize()
  }

  // 处理侧边栏大小变化
  const sidebarResizeHandler = (e) => {
    if (e.propertyName === 'width') {
      resizeHandler()
    }
  }

  // 初始化监听器
  const initListener = () => {
    resizeHandler = debounce(() => {
      resize()
    }, 100)
    window.addEventListener('resize', resizeHandler)

    sidebarElm.value = document.getElementsByClassName('sidebar-container')[0]
    sidebarElm.value?.addEventListener('transitionend', sidebarResizeHandler)
  }

  // 销毁监听器
  const destroyListener = () => {
    window.removeEventListener('resize', resizeHandler)
    resizeHandler = null

    sidebarElm.value?.removeEventListener('transitionend', sidebarResizeHandler)
  }

  onMounted(() => {
    initListener()
  })

  onBeforeUnmount(() => {
    destroyListener()
  })

  onActivated(() => {
    if (!resizeHandler) {
      initListener()
    }
    resize()
  })

  onDeactivated(() => {
    destroyListener()
  })

  return {
    resize
  }
}
